<?php
/**
 * Created by PhpStorm.
 * User: Raytine
 * Date: 2018/8/30
 * Time: 14:47
 */

namespace PddWechat\Models\User\Service;

use Dai\Framework\Base\BaseException;
use Dai\Framework\Base\BaseSessionInfo;
use PddWechat\Models\User\Data\BindBankCardData;
use PddWechat\Models\User\Data\UserData;
use PddWechat\Models\User\Data\WithdrawCashData;
use PddWechat\Models\User\DataObject\UserBankCardDo;
use PddWechat\Models\User\DataObject\UserWithdrawDo;
use PddWechat\Models\User\Param\WithdrawCashParam;

class WithdrawCash
{
    public function __construct()
    {
        $this->withdrawCashData = new WithdrawCashData();
        $this->userData = new UserData();
        $this->bindBankCardData = new BindBankCardData();
    }

    public function execute($basePageInfo) {
        /** @var BaseSessionInfo $sessionData */
        $sessionData = $basePageInfo->sessionInfo;
        $uid = $sessionData->uid;
        $openId = $sessionData->openId;
        $userInfo = $this->userData->getUserByOpenId($openId);
        if(empty($userInfo)) {
            return false;
        }
        $userMoney = $userInfo->userMoney;
        if($userMoney < 1) {
            throw new BaseException(BaseException::USER_WITHDRAW_LIMIT);
        }

        /** @var WithdrawCashParam $params*/
        $params = $basePageInfo->params;
        $withdrawMoney = $params->withdrawMoney;
        if($userMoney < $withdrawMoney) {
            return false;
        }

        /** @var UserBankCardDo $userBankCard*/
        $userBankCard = $this->bindBankCardData->selectByUid($uid);
        if(empty($userBankCard)) {
            return false;
        }
        $userWithdrawDo = new UserWithdrawDo();
        $userWithdrawDo->uid = $uid;
        $userWithdrawDo->withdrawMoney = $withdrawMoney;
        $userWithdrawDo->status = 0;
        $userWithdrawDo->bankCard = $userBankCard->bankCard;
        $userWithdrawDo->userName = $userBankCard->userName;
        return $this->withdrawCashData->withDrawMoney($userWithdrawDo,$uid, floatval($userMoney - $withdrawMoney));
    }
}